import 'package:flutter/material.dart';
import 'package:flutter_bilibili/util/color_util.dart';

/// 登录输入框
class LoginInput extends StatefulWidget {
  /// 左侧文本
  final String title;

  /// 输入框placeholder
  final String? hint;

  /// 输入框内容改变事件
  final ValueChanged<String>? onChanged;

  /// 输入框光标改变事件
  final ValueChanged<bool>? focusChanged;

  /// 下划线是否展开
  final bool? lineStretch;

  /// 是否密码框
  final bool? obscureText;

  /// 输入框类型，即键盘弹起类型
  final TextInputType? keyboardType;

  const LoginInput(
    this.title, {
    super.key,
    this.hint = '请输入内容！',
    this.onChanged,
    this.focusChanged,
    this.lineStretch = false,
    this.obscureText = false,
    this.keyboardType,
  });

  @override
  State<LoginInput> createState() => _LoginInputState();
}

class _LoginInputState extends State<LoginInput> {
  final _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();

    /// 监听是否获取光标
    _focusNode.addListener(() {
      if (widget.focusChanged != null) {
        widget.focusChanged!(_focusNode.hasFocus);
      }
    });
  }

  @override
  void dispose() {
    _focusNode.dispose(); // 销毁输入框
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Container(
              padding: const EdgeInsets.only(left: 15, right: 15),
              width: 120,
              child: Text(widget.title, style: const TextStyle(fontSize: 16)),
            ),
            _input()
          ],
        ),
        Padding(
          padding: EdgeInsets.only(
            left: !widget.lineStretch! ? 15 : 0,
            right: !widget.lineStretch! ? 15 : 0,
          ),
          child: const Divider(
            height: 1,
            thickness: 0.5,
          ),
        )
      ],
    );
  }

  /// 输入框
  _input() {
    return Expanded(
      child: TextField(
        focusNode: _focusNode,
        onChanged: widget.onChanged,
        obscureText: widget.obscureText!,
        keyboardType: widget.keyboardType,
        autofocus: !widget.obscureText!,
        cursorColor: primary,
        style: const TextStyle(
          fontSize: 16,
          color: Colors.black,
          fontWeight: FontWeight.w300,
        ),
        decoration: InputDecoration(
          contentPadding: const EdgeInsets.only(left: 20, right: 20),
          border: InputBorder.none,
          hintText: widget.hint ?? '',
          hintStyle: const TextStyle(fontSize: 15, color: Colors.grey),
        ),
      ),
    );
  }
}
